<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        title="购物车"
        @click-left="$router.go(-1)"
        left-arrow
      ></van-nav-bar>
    </header>
    <div class="content">
      <div class="noshop" v-if="!$store.state.users.login_state">
        <img src="https://img11.360buyimg.com/jdphoto/s180x180_jfs/t18163/292/540553659/74408/adeb7463/5a93c51cN3bb5e37b.png" alt="">
        <h3>
          您的购物车空空如也，请<router-link to="/home">选择商品</router-link>
        </h3>
        <h6 class="loginH">您还没有登录，点我登录吧</h6>
        <button class="goLogin" @click="$router.push('/login')">去登陆</button>
      </div>
      <div class="shopping" v-else>
        <van-notice-bar text="列表向左滑动可以删除商品" left-icon="volume-o :height=100%" mode="closeable"/>
        <van-swipe-cell v-for="(item, index) of cartlist" :key="item.cartid">
          <van-card
            :num="item.num"
            :price="item.price"
            :title="item.proname"
          >
            <div slot="thumb">
              <!-- <van-checkbox v-model="item.flag" @change="selectItem(item)"></van-checkbox> -->
              <input type="checkbox" v-model="item.flag" @change="selectItem(item, $event)">
              <img :src="item.proimg" alt="">
            </div>
            <div slot="tags">
              <van-tag plain type="danger">{{ item.brand }}</van-tag>
            </div>
            <div slot="footer">
              <van-button size="mini" @click="add(item)">+</van-button>
              <van-button :disable="item.num <= 1" size="mini" @click="reduce(item)">-</van-button>
            </div>
          </van-card>
          <template #right>
            <van-button
              square
              type="danger"
              text="删除"
              class="delete-button"
              @click="deleteItem(item.cartid, index)"
            />
          </template>
        </van-swipe-cell>
        <van-submit-bar
          :price="totalPrice * 100"
          :button-text="'去结算(' + totalNum + ')'"
          @submit="onSubmit"
        >
          <van-checkbox v-model="allchecked" @click="selectAll">全选</van-checkbox>
            <!-- <template #tip>
                你的收货地址不支持同城送, <span @click="onClickEditAddress">修改地址</span>
            </template> -->
        </van-submit-bar>
      </div>
       <h1 class="prolistTil">为你推荐</h1>
      <Prolist :prolist="prolist" ></Prolist>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import * as types from '@/store/mutation.types'
import Prolist from '@/components/prolist'
import { mapGetters } from 'vuex'
import { getCartData, updateCartData, deleteCartData, addOrder, getChecked, getallchecked, getProlist } from '@/api'
import { NavBar, Card, Tag, Button, NoticeBar, SwipeCell, Dialog, SubmitBar, Checkbox, Toast } from 'vant'
Vue.use(NavBar)
Vue.use(Card)
Vue.use(Tag)
Vue.use(Button)
Vue.use(NoticeBar)
Vue.use(SwipeCell)
Vue.use(Dialog)
Vue.use(SubmitBar)
Vue.use(Checkbox)
Vue.use(Toast)
export default {
  components: {
    Prolist
  },
  data () {
    return {
      cartlist: [],
      allchecked: Boolean,
      prolist: []
    }
  },
  computed: {
    ...mapGetters('cart', ['totalNum']),
    ...mapGetters('cart', ['totalPrice'])
    // ...mapState({
    //   cartlist: ({ cart }) => cart.cartlist,
    //   login_state: ({ users }) => users.login_state
    // }),
    // totalPrice () {
    //   return this.cartlist.reduce((sum, item) => {
    //     return item.flag ? sum + item.price * item.num : sum + 0
    //   }, 0)
    // }
    // totalNum () {
    //   return this.cartlist.reduce((sum, item) => {
    //     return item.flag ? sum + item.num : sum + 0
    //   }, 0)
    // }
  },
  mounted () {
    // if (!window.localStorage.getItem('userid')) {
    //   this.$router.push('/login')
    // }
    getCartData({
      userid: localStorage.getItem('userid')
    }).then(res => {
      this.cartlist = res.data.data
      // 通过单选框状态修改全选框状态
      this.$store.commit({
        type: 'cart/' + types.CHANGE_CART_LIST,
        payload: res.data.data
      })
      // console.log(this.$store.getters['cart/totalNum'])
      if (this.cartlist) {
        this.allchecked = this.cartlist.every(item => {
          return item.flag
        })
      }
    })
    getProlist().then(res => {
      console.log(res.data)
      this.prolist = res.data.data
    })
  },
  methods: {
    add (item) {
      // item.num += 1
      updateCartData({ cartid: item.cartid, num: item.num + 1 })
        .then(res => {
          console.log(res.data)
          if (res.data.code === '200') {
            item.num += 1
          }
        })
    },
    reduce (item) {
      // item.num -= 1
      updateCartData({
        cartid: item.cartid,
        num: item.num > 1 ? item.num - 1 : 1
      }).then(res => {
        console.log(res.data)
        if (res.data.code === '200') {
          item.num > 1 ? item.num -= 1 : item.num = 1
        }
      })
    },
    deleteItem (cartid, index) {
      Dialog.confirm({
        title: '删除',
        message: '你要删除该商品吗？'
      }).then(() => {
        deleteCartData({ cartid }).then(res => {
          if (res.data.code === '200') {
            this.cartlist.splice(index, 1)
          }
        })
      }).catch(() => {
        // on cancel
      })
    },
    selectItem (item, event) {
      getChecked({ cartid: item.cartid, flag: event.target.checked ? 1 : 0 }).then(res => { // 数据库更新完毕
        console.log(res.data)
        if (res.data.code === '200') {
          item.flag = event.target.checked
          if (event.target.checked) {
            this.allchecked = this.cartlist.every(item => {
              return item.flag
            })
          } else {
            this.allchecked = false
          }
        }
      })
    },
    selectAll () {
      this.allchecked = !this.allchecked
      const flag = this.allchecked ? 1 : 0
      const userid = localStorage.getItem('userid')
      getallchecked({ userid, flag }).then(res => {
        if (res.data.code === '200') {
          this.cartlist.map(item => {
            item.flag = this.allchecked
          })
        }
      })
    },
    onSubmit () {
      if (this.totalNum === 0) {
        Toast.fail('请先勾选你要购买的东西')
      } else {
        Toast('确认订单')
        const arr = []
        this.cartlist.map(item => {
          if (item.flag) {
            arr.push(item)
          }
        })
        addOrder({
          userid: localStorage.getItem('userid'),
          // 选中商品即为 arr
          orderlist: JSON.stringify(arr)
        }).then(res => {
          console.log(res)
          // 返回一个订单id，跳转页面传递订单id
          this.$router.push('/order/' + res.data.orderid)
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  background: #f4f4f4;
}
.delete-button {
  height: 100%;
}
.noshop {
  margin-top: 20px;
  text-align: center;
  img {
    width: 100px;
  }
}
.van-card {
  background:white;
}
.van-card__thumb {
  input {
    display: block;
    width: 30px;
    margin-top: 30%;
    transform: translateY(-50%);
    float: left;
  }
  img {
    display: block;
    width: 55px;
    float: left;
  }
}
.goLogin {
  width:80px;
  height:30px;
  border:none;
  border-radius: 15px;
  background:red;
  color:white;
  margin-top: 10px;
}
.loginH {
  margin-top: 50px;
}
.prolistTil {
  margin-top: 20px;
  text-align: center;
}
</style>
